package com.adun.springsecuritydemo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @author zhudunfeng
 * @date 2021/6/24 17:49
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据用户名去数据库查询，没有抛异常
        if(!"admin".equals(username)){
            throw new UsernameNotFoundException("用户名不存在");
        }

        //2.比较密码（注册时已经加密过），如果匹配成功返回UserDetails
        //正常是通过用户名去数据库查询password
        String password = passwordEncoder.encode("123");
        //最后一个参数是角色与权限
        //权限与角色通过ROLE_ 来进行区分,[严格区分大小写]
        return new User(username, password
                , AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_abc,/main.html," +
                "/insert,/delete"));
    }
}
